from rest_framework import serializers

from books.models import User, Type, House, Bookname, Books, Detail, Comment


class UserSer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
class TypeSer(serializers.Serializer):
    class Meta:
        model = Type
        fields = '__all__'

class HouseSer(serializers.Serializer):
    class Meta:
        model = House
        fields = '__all__'
class BooknameSer(serializers.Serializer):
    class Meta:
        model = Bookname
        fields = '__all__'
class BooksSer(serializers.Serializer):
    blist=serializers.SerializerMethodField(read_only=True)
    def get_blist(self,obj):
        return {'id':obj.id,'name':obj.name,'type':obj.type.name,'auther':obj.auther,'yi':obj.yi,'house':obj.house.name,'bookname':obj.bookname.name,'price':obj.price,'time':obj.time,'number':obj.number}
    class Meta:
        model = Books
        fields = '__all__'

class DetailSer(serializers.Serializer):
    detaillist=serializers.SerializerMethodField(read_only=True)
    def get_detaillist(self,obj):
        return {'name':obj.books.name,'type':obj.books.type.name,'auther':obj.books.auther,'house':obj.books.house.name,'bookname':obj.books.bookname.name,'price':obj.books.price,'number':obj.books.number,'isDian':obj.isDian,'isBorrow':obj.isBorrow}
    class Meta:
        model = Detail
        fields = '__all__'


class CommentSer(serializers.Serializer):
    commentlist=serializers.SerializerMethodField(read_only=True)
    def get_commentlist(self,obj):
        return {'user':obj.user.user,'name':obj.books.name,'comment':obj.comment,'time':obj.time}
    def create(self, validated_data):
        if 'request' in self.context:
            user = self.context['request'].user
            validated_data['user'] = user
        return Comment.objects.create(**validated_data)
    class Meta:
        model = Comment
        fields = '__all__'

